package com.github.prontera.service;

import java.text.MessageFormat;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.prontera.Shift;
import com.github.prontera.SpringUtils;
import com.github.prontera.StatusCode;
import com.github.prontera.domain.TalentOrder;
import com.github.prontera.domain.enums.ConsumeLevelTypeEnum;
import com.github.prontera.domain.enums.ConsumeSmallTypeEnum;
import com.github.prontera.domain.enums.ConsumeTypeEnum;
import com.github.prontera.domain.enums.OrderAcceptStatusEnum;
import com.github.prontera.domain.enums.OrderStatusEnum;
import com.github.prontera.domain.enums.PayStatusEnum;
import com.github.prontera.model.ConsumeMessageTemplate;
import com.github.prontera.persistence.CrudMapper;
import com.github.prontera.persistence.TalentOrderMapper;

/**
 * 角色
 */
@Service
@Transactional
public class TalentOrderService extends CrudServiceImpl<TalentOrder> {

	@Autowired
	private TalentOrderMapper mapper;
	@Autowired
	private ClientService clientService;
	@Autowired
	private ConsumeService consumeService;
	
	@Autowired
	private static Map<Long, TalentOrder> tMap=new HashMap<Long, TalentOrder>();
	
	@Autowired
	public TalentOrderService(CrudMapper<TalentOrder> mapper) {
		super(mapper);
	}

	public List<TalentOrder> findClientOrder(TalentOrder talentOrder) {
		return mapper.findClientOrder(talentOrder);
	}
	
	public List<TalentOrder> findAcceptClientOrder(TalentOrder talentOrder) {
		return mapper.findAcceptClientOrder(talentOrder);
	}
	
	public Boolean insertOrder(TalentOrder order) {
		boolean success= insert(order)>0;
		updateMemoryOrder(order);
		return success;
	}
	
	public void loadMemorypdateOrderStatus() {
		List<OrderStatusEnum> aEnums=new ArrayList<OrderStatusEnum>();
		aEnums.add(OrderStatusEnum.FINISHED);
		aEnums.add(OrderStatusEnum.REFUNDS);
		TalentOrder talentOrder=new TalentOrder();
		talentOrder.setNotInStatus(aEnums);
		talentOrder.setPageSize(Integer.MAX_VALUE);
		List<TalentOrder> talentOrders=	mapper.find(talentOrder);
		talentOrders.forEach(order->{
			tMap.put(order.getId(), order);
		});
	}
	
	public void updateMemoryOrder(TalentOrder order) {
		tMap.put(order.getId(), order);
	}
	
	public void updateMemoryOrderStatus() {
		tMap.forEach((id,order)->{
		    if((order.getPayStatus()==PayStatusEnum.WAIT_PAYMENT||order.getPayStatus()==PayStatusEnum.PAYMENT_FAIL) &&order.getStatus()==OrderStatusEnum.CONFIRMED
		    		&&OffsetDateTime.now().minusMinutes(10).isAfter(order.getCreateTime())){//未付款超时订单
		    	
		    	order.setReason("未付款超时订单");
				order.setAcceptStatus(OrderAcceptStatusEnum.FINISHED);
				order.setStatus(OrderStatusEnum.FINISHED);
				order.setScore(0);
				
				System.out.println("------未付款超时订单------");
				
				SpringUtils.getBean(TalentOrderService.class).update(order);
				
				updateMemoryOrder(order);
				
		    }else if(order.getAcceptStatus()==OrderAcceptStatusEnum.UNACCEPTED
		    		&&OffsetDateTime.now().minusHours(48).isAfter(order.getCreateTime())){//未接受超时订单
		    	order.setReason("未接受超时订单");
				order.setAcceptStatus(OrderAcceptStatusEnum.FINISHED);
				order.setStatus(OrderStatusEnum.FINISHED);
				order.setScore(0);
				System.out.println("------未接受超时订单------");
				
				SpringUtils.getBean(TalentOrderService.class).update(order);
				SpringUtils.getBean(ClientService.class).updateAmount(order.getClientId(), order.getAmount());
				//自己得消费记录
				SpringUtils.getBean(ConsumeService.class).insertConsume(order.getClientId(),ConsumeSmallTypeEnum.DEPOSIT,MessageFormat.format(ConsumeMessageTemplate.MSG_DEPOSIT_TALENT_ORDER,order.getAmount().doubleValue())
						,ConsumeLevelTypeEnum.BALANCE, null,  order.getAmount(),ConsumeTypeEnum.INCOME,null);
		   
				updateMemoryOrder(order);
				
		    }else if(order.getStatus()==OrderStatusEnum.FINISHED
		    		&&OffsetDateTime.now().minusHours(48).isAfter(order.getStartTime().plusHours(order.getTimeDuration()))){//未确认超时订单
		    	order.setReason("未确认超时订单");
				order.setAcceptStatus(OrderAcceptStatusEnum.FINISHED);
				order.setStatus(OrderStatusEnum.FINISHED);
				order.setScore(0);
				System.out.println("------未确认超时订单------");
				
				SpringUtils.getBean(TalentOrderService.class).update(order);
				
				
				updateMemoryOrder(order);
		    }
		});
	}
	
	/**
	 * 达人订单申请退款
	 */
	public Boolean refund(TalentOrder order) {
		order.setReason("用户主动退款");
		order.setPayStatus(PayStatusEnum.REFUND_PAYMENT);
		order.setAcceptStatus(OrderAcceptStatusEnum.FINISHED);
		order.setStatus(OrderStatusEnum.FINISHED);
		order.setRefundPaymentTime(OffsetDateTime.now());
		order.setStatus(OrderStatusEnum.FINISHED);
		if(update(order)<=0){
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "参数有误,请重试");
		};
		if(!clientService.updateAmount(order.getClientId(), order.getAmount())){
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "参数有误,请重试");
		};
		//自己得消费记录
		consumeService.insertConsume(order.getClientId(),ConsumeSmallTypeEnum.BUY_TALEND,MessageFormat.format(ConsumeMessageTemplate.MSG_DEPOSIT_TALENT_ORDER,order.getAmount().doubleValue())
				,ConsumeLevelTypeEnum.BALANCE, null,  order.getAmount(),ConsumeTypeEnum.INCOME,null);
		return true;
	}
	
	/**
	 * 更新超时"未接受"订单
	 */
	public void updateTimeoutOrder(){
		List<TalentOrder> orders=SpringUtils.getBean(TalentOrderMapper.class).findTimeoutOrder();
		if(orders!=null){
			for (TalentOrder order : orders) {
				order.setReason("未接受超时订单");
				order.setAcceptStatus(OrderAcceptStatusEnum.UNACCEPTED);
				order.setStatus(OrderStatusEnum.FINISHED);
				SpringUtils.getBean(TalentOrderService.class).update(order);
				SpringUtils.getBean(ClientService.class).updateAmount(order.getClientId(), order.getAmount());
				//自己得消费记录
				SpringUtils.getBean(ConsumeService.class).insertConsume(order.getClientId(),ConsumeSmallTypeEnum.DEPOSIT,MessageFormat.format(ConsumeMessageTemplate.MSG_DEPOSIT_TALENT_ORDER,order.getAmount().doubleValue())
						,ConsumeLevelTypeEnum.BALANCE, null,  order.getAmount(),ConsumeTypeEnum.INCOME,null);
			}
		}
	}
	
	/**
	 * 更新超时"确认"订单
	 */
	public void updateNotEndTimeoutOrder(){
		List<TalentOrder> orders=SpringUtils.getBean(TalentOrderMapper.class).findNotEndTimeoutOrder();
		if(orders!=null){
			for (TalentOrder order : orders) {
				order.setReason("未确认超时订单");
				order.setAcceptStatus(OrderAcceptStatusEnum.FINISHED);
				order.setStatus(OrderStatusEnum.FINISHED);
				SpringUtils.getBean(TalentOrderService.class).update(order);
			}
		}
	}

	
	/**
	 * 更新超时"未支付"订单
	 */
	public void updateNotStartTimeoutOrder(){
		List<TalentOrder> orders=SpringUtils.getBean(TalentOrderMapper.class).findNotStartTimeoutOrder();
		if(orders!=null){
			for (TalentOrder order : orders) {
				order.setReason("未付款超时订单");
				order.setAcceptStatus(OrderAcceptStatusEnum.UNACCEPTED);
				order.setStatus(OrderStatusEnum.FINISHED);
				SpringUtils.getBean(TalentOrderService.class).update(order);
			}
		}
	}

	public void updateTimeoutOrder(TalentOrder findOrder) {
		update(findOrder);
		SpringUtils.getBean(ClientService.class).updateAmount(findOrder.getClientId(), findOrder.getAmount());
		//自己得消费记录
		SpringUtils.getBean(ConsumeService.class).insertConsume(findOrder.getClientId(),ConsumeSmallTypeEnum.DEPOSIT,MessageFormat.format(ConsumeMessageTemplate.MSG_DEPOSIT_TALENT_ORDER,findOrder.getAmount().doubleValue())
				,ConsumeLevelTypeEnum.BALANCE, null,  findOrder.getAmount(),ConsumeTypeEnum.INCOME,null);		
	}

	public Integer updateByTradeNo(TalentOrder talentOrder) {
		return mapper.updateByTradeNo(talentOrder);
	}


}
